<template>
  <el-dialog v-model="dialogVisible" title="修改产品信息" width="500" draggable overflow>
    <template #header>
      <div class="dialog-header">
        <div class="dialog-title">修改产品信息</div>
      </div>
    </template>
    <el-form :model="form" label-width="80px">
      <!-- Product Name -->
      <el-form-item label="产品名">
        <el-input v-model="form.productName" autocomplete="off"/>
      </el-form-item>
      <!-- Brand ID -->
      <el-form-item label="品牌ID">
        <el-input v-model="form.brandId" autocomplete="off"/>
      </el-form-item>
      <!-- Product Cover Image -->
      <el-form-item label="产品封面">
        <div v-if="isShowOld">
          <img class="pic" :src="form.productImg" alt=""/>
          <el-button type="primary" @click="updateImg">修改封面</el-button>
        </div>
        <div v-else>
          <upload ref="uploadComponent" @upload-success="handleUploadSuccess"></upload>
        </div>
      </el-form-item>
      <!-- Category ID -->
      <el-form-item label="类别ID">
        <el-input v-model="form.categoryId" autocomplete="off"/>
      </el-form-item>
      <!-- Model Number -->
      <el-form-item label="型号">
        <el-input v-model="form.modelNumber" autocomplete="off"/>
      </el-form-item>
      <!-- Unit -->
      <el-form-item label="单位">
        <el-input v-model="form.unit" autocomplete="off"/>
      </el-form-item>
      <!-- Market Price -->
      <el-form-item label="市场价">
        <el-input v-model="form.marketPrice" autocomplete="off"/>
      </el-form-item>
      <!-- Selling Price -->
      <el-form-item label="销售价">
        <el-input v-model="form.sellingPrice" autocomplete="off"/>
      </el-form-item>
      <!-- Cost Price -->
      <el-form-item label="成本价">
        <el-input v-model="form.costPrice" autocomplete="off"/>
      </el-form-item>
      <!-- Product Description -->
      <el-form-item label="产品描述">
        <el-input type="textarea" v-model="form.productDescription" autocomplete="off"/>
      </el-form-item>
      <!-- Stock -->
      <el-form-item label="库存">
        <el-input v-model="form.stock" autocomplete="off"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitEdit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {defineProps, defineEmits, watch, reactive, computed, ref} from 'vue';
import {deleteFile} from '@/api/utils';
import {updateProduct} from '@/api/product'
import {headImgStore} from '@/store/tokenStore';
import upload from "@/components/upload.vue";
import {ElMessage} from "element-plus";

// 定义props
const props = defineProps({
  drawerVisible: Boolean,
  product: {
    type: Object as () => {
      productId: number;
      productName: string;
      brandId: number | null;
      categoryId: number | null;
      productImg: String;
      modelNumber: string;
      unit: string;
      marketPrice: number | null;
      sellingPrice: number | null;
      costPrice: number | null;
      productDescription: string;
      stock: number | null;
    },
    required: true
  }
});

// 定义emits
const emit = defineEmits(['update:drawerVisible', 'formSubmitted']);

// 初始化表单数据
const form = reactive({...props.product});

// 监听 props 变化，当有新的 product 传入时更新表单
watch(
    () => props.product,
    (newVal) => {
  if (newVal) {
    Object.assign(form, newVal);
  }
}, {immediate: true, deep: true}
);

// 计算属性来同步 dialogVisible 和父组件的状态
const dialogVisible = computed({
  get: () => props.drawerVisible,
  set: (value) => emit('update:drawerVisible', value)
});

// 控制是否显示旧封面
const isShowOld = ref(true);

// 更新图片的方法
const updateImg = async () => {
  isShowOld.value = false;
};

// 关闭对话框的方法
const closeDialog = () => {
  dialogVisible.value = false;
};

// 引用子组件实例
const uploadComponent = ref<InstanceType<typeof upload> | null>(null);

// 获取头部图片存储
const headImg = headImgStore();

// 图片上传成功的回调方法
const handleUploadSuccess = () => {
  // 这里可以添加处理上传成功的逻辑
};

// 提交编辑的方法
const submitEdit = async () => {
  try {
    let tempImg = form.productImg;
    if (uploadComponent.value && !isShowOld.value) {
      // 使用Promise等待上传完成
      const uploadPromise = new Promise<void>((resolve, reject) => {
        let unwatch: (() => void) | null = null; // 提前声明unwatch
        unwatch = watch(
            () => headImg.headImg,
            (newVal) => {
              if (newVal) {
                if (unwatch) unwatch(); // 确保unwatch已初始化
                resolve();
              }
            },
            {immediate: true}
        );

        // 调用子组件的manualUpload方法并立即启动上传
        uploadComponent.value.manualUpload();
      });

      await uploadPromise; // 等待上传完成
    }
    if (headImg.headImg !== '') {
      form.productImg = headImg.headImg;
    } else {
      form.productImg = tempImg;
    }
    // 更新产品信息
    await updateProduct(form, form.productId);
    // 模拟成功后刷新列表
    emit('formSubmitted');
    closeDialog();
    deleteImg(tempImg)
    headImg.clearHeadImg();
    isShowOld.value = true;
  } catch (error) {
    ElMessage.error('提交失败，请检查输入信息或网络连接');
    console.error(error); // 记录错误信息，方便调试
  }
};
const deleteImg = async (tempImg) => {
  let fileName = tempImg.split('/').pop();
  if (fileName) {
    const res = await deleteFile(fileName);
    console.log(res);
  }
};
</script>

<style scoped>
.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-title {
  font-size: 18px;
  font-weight: bold;
}

.pic {
  width: 100px;
  height: 100px;
}
</style>